package com.tron.dobest.java.tronangent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class SimpleJDKDynamicProxyDemo {
    interface IService {
        void sayHello();
    }

    static class RealService implements IService {
        @Override
        public void sayHello() {
            System.out.println("真实服务sayHello");
        }
    }

    static class SimpleInvocationHandler implements InvocationHandler {
        private Object realObject;

        public SimpleInvocationHandler(Object realObject) {
            this.realObject = realObject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("代理方法start");
            Object result = method.invoke(realObject, args);
            System.out.println("代理方法end");
            return result;
        }
    }

    public static void main(String[] args) {
        /**
         * 只能为接口创建代理对象，返回的代理对象也只能转换为接口类型
         */
        IService realService = new RealService();
        IService proxyInstance = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class<?>[]{IService.class}, new SimpleInvocationHandler(realService));
        proxyInstance.sayHello();
    }
}
